import logging, sys
import time
import grpc
from proto import detect_pb2
from proto import detect_pb2_grpc
import cv2
import numpy as np


def mat2bytes(image: np.ndarray) -> bytes:
    return np.array(cv2.imencode('.jpg', image)[1]).tobytes()

def bytes2mat(image: bytes) -> np.ndarray:
    return cv2.imdecode(np.array(bytearray(image), dtype='uint8'), cv2.IMREAD_UNCHANGED)


def DetectOperation(signal, channel_n_port):

    with grpc.insecure_channel(channel_n_port) as channel:
        stub = detect_pb2_grpc.DetectServiceStub(channel)
        requests = detect_pb2.DetectRequest(detect_signal=signal)
        # try:
        response = stub.DetectOperation(requests)
        frame = bytes2mat(response.processed_img)
        cv2.imshow('box', frame)
        cv2.waitKey()
        print(response.abnormal_signal)
        print(response.results)
        # logging.info('response flag' + response)
        # except:
        #     print('response error!')
        #     logging.info('response error!')

if __name__ =='__main__':
    DetectOperation(True, 'localhost:6667')